package com.wpp.concurrent.util.semaphoredemo;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 *  Semaphore也就是信号量，提供了资源数量的并发访问控制
 */
public class Main {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);

        for (int i = 0; i < 5; i++) {
            new MyThread("学生-" + (i + 1), semaphore).start();
        }
    }
}
class MyThread extends Thread {
    private final Semaphore semaphore;
    private final Random random = new Random();

    public MyThread(String name, Semaphore semaphore) {
        super(name);
        this.semaphore = semaphore;
    }
    @Override
    public void run() {
        try {
            // 获取信标：抢座
            semaphore.acquire();
            // 抢到之后开始写作业
            System.out.println(Thread.currentThread().getName() + " - 抢到了座位，开始写作业");
            Thread.sleep(random.nextInt(1000));
            System.out.println(Thread.currentThread().getName() + " - 作业写完，腾出座位");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 释放信标：腾出座位
        semaphore.release();
    }
}
